using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Services.Localization;
using NEvoWeb.Modules.NB_Store;

namespace Nevoweb.Modules.NB_Store.CategoryFilter
{
    public partial class View : BaseModule
    {
        private TreeView _tView;
        private String _catfilter = "";
        private String _search = "";
        private Button cmdSearch = new Button();
        private Button cmdClear = new Button();
        private TextBox txtSearch = new TextBox();
        private Boolean _casCade = false;

        protected void Page_Init(object sender, EventArgs e)
        {
            cmdSearch.CssClass = "nb-catfilter-search";
            cmdSearch.Text = GetLocalizedString("cmdSearch");
            cmdSearch.Click += new EventHandler(CmdSearchClick);

            cmdClear.CssClass = "nb-catfilter-clear";
            cmdClear.Text = GetLocalizedString("cmdClear");
            cmdClear.Click += new EventHandler(CmdClearClick);

            _catfilter = RequestQueryStringParam(Request, "catfilter");
            _search = RequestQueryStringParam(Request, "search");
        }


        protected void Page_Load(object sender, EventArgs e)
        {

            // Build Template html with controls controls
            var strTempl = "";
            if (Settings["txtTemplateText"] != null) strTempl = Settings["txtTemplateText"].ToString();
            var aryS = ParseTemplateText(strTempl);
            var ctl1 = false; var ctl2 = false; var ctl3 = false; var ctl4 = false;
            foreach (var s in aryS)
            {
                if (s.StartsWith("tag:"))
                {
                    if (s == "tag:categorytree" && !ctl1)
                    {
                        ctl1 = true;
                        var strDepth = "2";Double retNum;
                        if (Settings["txtDepth"] != null) strDepth = Settings["txtDepth"].ToString();
                        if (!Double.TryParse(Convert.ToString(strDepth), NumberStyles.Any, CultureInfo.InvariantCulture, out retNum)) strDepth = "2";
                        _tView = GetCategoryTreeview(Convert.ToInt32(strDepth));
                        _tView.CssClass = "nb-catfilter-tree";
                        phCatSelect.Controls.Add(_tView);                        
                    }
                    if (s == "tag:search" && !ctl2)
                    {
                        ctl2 = true;
                        phCatSelect.Controls.Add(txtSearch);
                    }
                    if (s == "tag:searchbutton" && !ctl3)
                    {
                        ctl3 = true;
                        phCatSelect.Controls.Add(cmdSearch);
                    }
                    if (s == "tag:clearbutton" && !ctl4)
                    {
                        ctl4 = true;
                        phCatSelect.Controls.Add(cmdClear);
                    }
                }
                else
                {
                    var l = new Literal();
                    l.Text = s;
                    phCatSelect.Controls.Add(l);
                }
            }

            if (Settings["chkCasCade"] != null) _casCade = Convert.ToBoolean(Settings["chkCasCade"].ToString());


            if (!Page.IsPostBack) txtSearch.Text = _search;
        }


        private void CmdSearchClick(object sender, EventArgs e)
        {
            var catlist = "";

            var orderByQuery = RequestQueryStringParam(Request, "orderby");
            var orderDescQuery = RequestQueryStringParam(Request,"desc");

            foreach (TreeNode tn in _tView.CheckedNodes)
            {
                if (tn.Checked) catlist += tn.Value + ",";
            }

            if (_casCade)
            {
                //cascading search on category selected
                var currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
                var objCtrl = new CategoryController();
                var aryCatList = objCtrl.GetCategories(PortalId, currentCulture, -1, false, false);
                var slist = catlist.Split(',');
                foreach (var c in slist)
                {
                    if (c != "") catlist += objCtrl.GetSubCategoryList(aryCatList, Convert.ToInt32(c));
                }
            }

            catlist = catlist.TrimEnd(',');


            var redirectTabId = "";Double retNum;
            if (Settings["txtTabId"] != null) redirectTabId = Settings["txtTabId"].ToString();
            if (!Double.TryParse(Convert.ToString(redirectTabId), NumberStyles.Any, CultureInfo.InvariantCulture, out retNum)) redirectTabId = TabId.ToString();

            var paramL = new List<String>();
            if (txtSearch.Text != "") paramL.Add("search=" + txtSearch.Text.Trim());
            if (catlist != "") paramL.Add("catfilter=" + catlist);
            if (orderByQuery != "") paramL.Add("orderby=" + orderByQuery);
            if (orderDescQuery != "") paramL.Add("desc=1");
            var blnAndMode = false;
            if (Settings["chkAndMode"] != null && Settings["chkAndMode"].ToString().ToLower() == "true") paramL.Add("andmode=1");

            var param = new string[paramL.Count]; var i = 0;
            foreach(var s in paramL)
            {
                param[i] = s;i++;
            }

            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(Convert.ToInt32(redirectTabId), "", param),true);
        }

        private void CmdClearClick(object sender, EventArgs e)
        {
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(TabId), true);
        }


        private TreeView GetCategoryTreeview(int depth)
        {
            var tView = new TreeView();
            tView.Nodes.Clear();

            var currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
            var objCtrl = new CategoryController();

            var aryCatList = objCtrl.GetCategories(PortalId, currentCulture, -1, false, false);
            BuildTreeView(aryCatList, tView,0,null,depth);
            tView.ExpandAll();
            tView.ShowExpandCollapse = false;            
            return tView;
        }

        private void BuildTreeView(ArrayList aryCatList, TreeView tView, int ParentId = 0, TreeNode parentNode = null,int depth = 2)
        {
            if (depth > 0)
            {

                if (parentNode == null) ParentId = 0;
                foreach (NB_Store_CategoriesInfo catInfo in aryCatList)
                {
                    if (catInfo.ParentCategoryID == ParentId)
                    {
                        //must be root node
                        var tn = new TreeNode();
                        tn.Text = catInfo.CategoryName;
                        tn.Value = catInfo.CategoryID.ToString();
                        tn.ShowCheckBox = true;
                        tn.Checked = false;
                        tn.SelectAction = TreeNodeSelectAction.None;

                        if (("," + _catfilter + ",").Contains("," + catInfo.CategoryID.ToString() + ","))
                        {
                            tn.Checked = true;
                        }

                        if (parentNode == null)
                        {                            
                            tView.Nodes.Add(tn);
                        }
                        else
                        {
                            parentNode.ChildNodes.Add(tn);
                        }

                        BuildTreeView(aryCatList, tView, catInfo.CategoryID, tn, depth - 1);

                    }
                }
            }
        }

        public static string RequestQueryStringParam(System.Web.HttpRequest Request, string paramName)
        {
            var result = String.Empty;

            if (Request.QueryString.Count != 0)
            {
                result = Convert.ToString(Request.QueryString[paramName]);
            }

            return (result == null) ? String.Empty : result.Trim();
        }

        public static string[] ParseTemplateText(string templText)
        {
            char[] paramAry = { Convert.ToChar("["), Convert.ToChar("]") };

            //use double sqr brqckets as escape char.
            var foundEscapeChar = false;
            if (templText.IndexOf("[[", StringComparison.Ordinal) > 0 | templText.IndexOf("]]", StringComparison.Ordinal) > 0)
            {
                templText = templText.Replace("[[", "**SQROPEN**");
                templText = templText.Replace("]]", "**SQRCLOSE**");
                foundEscapeChar = true;
            }

            var strOut = templText.Split(paramAry);

            if (foundEscapeChar)
            {
                for (var lp = 0; lp <= strOut.GetUpperBound(0); lp++)
                {
                    if (strOut[lp].Contains("**SQROPEN**"))
                    {
                        strOut[lp] = strOut[lp].Replace("**SQROPEN**", "[");
                    }
                    if (strOut[lp].Contains("**SQRCLOSE**"))
                    {
                        strOut[lp] = strOut[lp].Replace("**SQRCLOSE**", "]");
                    }
                }
            }

            return strOut;
        }

        private string GetLocalizedString(string str)
        {
            var localizedString = Localization.GetString(str, LocalResourceFile);
            return (string.IsNullOrEmpty(localizedString) ? str : localizedString);
        }
    }
}
